package open.douban.hashtree;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

/**
 * can avoid too many null node when leaf(element) is not so many.
 * 
 */
public class HashTreeInMap extends HashTree {

	private HashMap<Integer, Node> tree = null;

	public HashTreeInMap(String path) throws IOException {
		// take it easy, can not use template method pattern for this
		// Do not call sub-class method in parent constructor for the object in
		// sub-class is not
		// constructed.
		super(path, true);

		init();
		build();
	}

	@Override
	protected void enlarge() {
		// do nothing
	}

	@Override
	protected void init() {
		tree = new HashMap<Integer, Node>();
	}

	@Override
	public BSTIterator iterator() {
		BSTIterator it = new BSTIterator() {
			Iterator<Integer> iterator = tree.keySet().iterator();

			@Override
			public boolean hasNext() {
				return iterator.hasNext();
			}

			@Override
			public Node next() {
				return tree.get(iterator.next());
			}

		};

		return it;
	}

	@Override
	protected Node node(int id) {
		return tree.get(id);
	}

	@Override
	protected void node(int id, Node n) {
		tree.put(id, n);
	}

	@Override
	protected void remove(int id) {
		tree.remove(id);
	}

	@Override
	public int getNodeNumber() {
		return tree.size();
	}
}
